﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using log4net;

using JsonServer.Interfaces;


namespace AshxWebApp01
{
    /// <summary>
    /// Summary description for ApiHandler
    /// </summary>
    public class ApiHandler : IHttpHandler
    {
        #region Logging
        protected static readonly ILog _log = LogManager.GetLogger(typeof(ApiHandler));
        #endregion

        #region State
        #endregion

        #region CtorDtor
        static ApiHandler()
        {
        }
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var ajaxHeader = context.Request.Headers["X-Requested-With"];
                if ("XMLHttpRequest" == ajaxHeader)
                {
                    var services = (IDictionary<string, JsonServerApi>)context.Application[Global.JSON_SERVERS];
                    var args = new Dictionary<string, string>();

                    context.Response.Buffer = false;
                    context.Response.BufferOutput = false;

                    //context.Response.ContentType = "text/json";
                    context.Response.ContentType = "application/json";

                    //context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    context.Response.ContentEncoding = System.Text.Encoding.ASCII;

                    // get arguments
                    foreach (var key in context.Request.QueryString.AllKeys)
                    {
                        args[key] = context.Request.QueryString[key];
                    }

                    var service = context.Request.Url.Segments[context.Request.Url.Segments.Length - 2];
                    service = service.Replace("/", "");
                    var method = context.Request.Url.Segments[context.Request.Url.Segments.Length - 1];
                    method = method.Replace("/", "");

                    if (services.ContainsKey(service))
                    {
                        if (services[service].ContainsKey(method))
                        {
                            services[service][method](args, context.Request.InputStream, context.Response.OutputStream);
                        }
                        else
                        {
                            _log.WarnFormat("Unknown method [{0}] requested in ProcessRequest() for serivice: [{1}]...what to do here?", method, service);
                        }
                    }
                    else
                    {
                        _log.WarnFormat("Unknown service [{0}] requested in ProcessRequest()...what to do here?", service);
                    }

                    context.Response.Flush();
                }
                else
                {
                    // go find file or somesuch
                }
            }
            catch (Exception e)
            {
                _log.Error("Unexpected exception in ProcessRequest()", e);
                throw;
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}